package com.iot.web.controller.device;

import com.alibaba.fastjson.JSONObject;
import com.iot.common.annotation.Log;
import com.iot.common.core.controller.BaseController;
import com.iot.common.core.domain.AjaxResult;
import com.iot.common.core.domain.entity.SysUser;
import com.iot.common.enums.BusinessType;
import com.iot.common.utils.DateUtils;
import com.iot.common.utils.SecurityUtils;
import com.iot.common.utils.TimeHelper;
import com.iot.common.utils.poi.ExcelUtil;
import com.iot.device.domain.*;
import com.iot.device.dto.GasClientDataStatistics;
import com.iot.device.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *
 * @author iot
 * @date 2023-04-14
 */
@RestController
@RequestMapping("/visual/statisticsBeidou")
public class StatisticsBeidouController extends BaseController
{

    @Autowired
    public IBeidouClientService beidouClientService;
    @Autowired
    public IBeidouEventService beidouEventService;
    @Autowired
    public IStatisticsService statisticsService;


    /**
     * 查询设备统计
     */
    @GetMapping("/deviceStat")
    public AjaxResult deviceStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Map<String, Long> clientStatistics = beidouClientService.selectBeidouClientStatistics(sysUser.isAdmin() ? null : sysUser.getUserId());
        JSONObject obj = new JSONObject();
        obj.put("totalCount", clientStatistics.getOrDefault("totalCount", 0L));
        obj.put("totalOnlineCount", clientStatistics.getOrDefault("onlineCount", 0L));
        return AjaxResult.success(obj);
    }

    /**
     * 首页查询报警数据
     */
    @GetMapping("/totalEvent")
    public AjaxResult totalEvent()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEvent(null, DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEvent(sysUser.getUserId(), DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/dataVisual")
    public AjaxResult dataVisual()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        BeidouClient queryBeidouClient = new BeidouClient();
        if(!sysUser.isAdmin()){
            queryBeidouClient.setUserId(sysUser.getUserId());
        }
        Date now = DateUtils.getNowDate();
        List<BeidouClient> beidouClientList = beidouClientService.selectBeidouClientList(queryBeidouClient);
        TimeHelper.start("beidouEventService.selectRecentBeidouEventList");
        List<BeidouEvent> beidouEventList = beidouEventService.selectRecentBeidouEventList(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
//        System.out.println("beidouEventService.selectRecentBeidouEventList执行耗时：" + TimeHelper.end("beidouEventService.selectRecentBeidouEventList"));
        TimeHelper.start("statisticsService.selectBeidouEventThisYearStatistics");
        Map<String, Object> beidouEventThisYearStatistics = statisticsService.selectBeidouEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
//        System.out.println("statisticsService.selectBeidouEventThisYearStatistics执行耗时：" + TimeHelper.end("statisticsService.selectBeidouEventThisYearStatistics"));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        beidouEventThisYearStatistics.put("thisMonth", thisMonth);
        beidouEventThisYearStatistics.put("lastMonth", lastMonth);
        JSONObject data = new JSONObject();
        data.put("beidouClientList", beidouClientList);
        data.put("beidouEventList", beidouEventList);
        data.put("beidouEventThisYearStatistics", beidouEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/visualStatistics")
    public AjaxResult visualStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Long> countBeidouClient = beidouClientService.countBeidouClientsByUserId(sysUser.isAdmin() ? null : sysUser.getUserId());
        List<Map<String, Long>> eventRank = beidouEventService.selectBeidouEventRankByClient(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        Map<String, Object> beidouEventThisYearStatistics = statisticsService.selectBeidouEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        JSONObject data = new JSONObject();
        data.put("countBeidouClient", countBeidouClient);
        data.put("eventRank", eventRank);
        data.put("beidouEventThisYearStatistics", beidouEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     *
     */
    @GetMapping("/thisYearEventStatistics")
    public AjaxResult thisYearEventStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Object> beidouEventThisYearStatistics = statisticsService.selectBeidouEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        beidouEventThisYearStatistics.put("thisMonth", thisMonth);
        beidouEventThisYearStatistics.put("lastMonth", lastMonth);
        return AjaxResult.success(beidouEventThisYearStatistics);
    }



    /**
     * 环境监测报警近30日数据趋势
     */
    @GetMapping("/thirtyDaysEventTrend")
    public AjaxResult thirtyDaysEventTrend()
    {
        Date now = DateUtils.getNowDate();
        // 近三十天事件
        Date startTime = DateUtils.getTimesmorning(DateUtils.addDays(now, -31));
        Date endTime = DateUtils.getTimesnight(DateUtils.addDays(now, -1));
        SysUser sysUser = SecurityUtils.getSysUser();
        TimeHelper.start("statisticsService.selectBeidouEventTrendStatisticsByDuration");
        List<Map<String, Object>> thirtyDaysChangeList = statisticsService.selectBeidouEventTrendStatisticsByDuration(startTime, endTime, sysUser.isAdmin() ? null : sysUser.getUserId());
        System.out.println("statisticsService.selectBeidouEventTrendStatisticsByDuration执行耗时：" + TimeHelper.end("statisticsService.selectBeidouEventTrendStatisticsByDuration"));
        TreeMap<String, Map<String, Long>> thirtyDaysChange = new TreeMap(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return DateUtils.parseDate(o1).compareTo(DateUtils.parseDate(o2));
            }
        });
        List<String> days = DateUtils.getDayListOfDate(startTime, endTime);
        for(String day : days){
            thirtyDaysChange.put(day, null);
        }
        for(Map<String, Object> map : thirtyDaysChangeList){
            if(map.get("eventDate") == null){
                continue;
            }
            String date = map.get("eventDate").toString();
            Long position = Long.parseLong(map.get("position").toString());
            Long Ii = Long.parseLong(map.get("Ii").toString());
            Long angle = Long.parseLong(map.get("angle").toString());
            Map<String, Long> m = new HashMap();
            m.put("position", position);
            m.put("Ii", Ii);
            m.put("angle", angle);
            m.put("total", position + angle + Ii);
            thirtyDaysChange.put(date, m);
        }
        JSONObject data = new JSONObject();
        data.put("days", days);
        List<Long> IiList = new ArrayList<>();
        List<Long> positionList = new ArrayList<>();
        List<Long> angleList = new ArrayList<>();
        List<Long> totalList = new ArrayList<>();
        for(String day : days){
            Map<String, Long> dayData = thirtyDaysChange.get(day);
            IiList.add(dayData == null ? 0L : dayData.get("Ii"));
            positionList.add(dayData == null ? 0L : dayData.get("position"));
            angleList.add(dayData == null ? 0L : dayData.get("angle"));
            totalList.add(dayData == null ? 0L : dayData.get("total"));
        }
        // data.put("thirtyDaysChange", thirtyDaysChange);
        data.put("IiList", IiList);
        data.put("positionList", positionList);
        data.put("angleList", angleList);
        data.put("totalList", totalList);
        return AjaxResult.success(data);
    }


    /**
     * 报警数据分类统计（全部）
     */
    @GetMapping("/eventStat")
    public AjaxResult eventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEventGroupByType(null));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEventGroupByType(sysUser.getUserId()));
        }
    }

    /**
     * 报警数据分类统计（本日）
     */
    @GetMapping("/todayEventStat")
    public AjaxResult todayEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTodayBeidouEventGroupByType(null, DateUtils.getTimesmorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTodayBeidouEventGroupByType(sysUser.getUserId(), DateUtils.getTimesmorning(now)));
        }
    }

    /**
     * 报警数据分类统计（本月）
     */
    @GetMapping("/monthEventStat")
    public AjaxResult monthEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsMonthBeidouEventGroupByType(null, DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsMonthBeidouEventGroupByType(sysUser.getUserId(), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
}
